package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFName;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wmz
 * @date 2024/1/30 19:19
 * @description ReportServiceImpl
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = getLocalDates(begin, end);

        //设置每日营业额
        List<Double> turnoverList = new ArrayList<>();
        if(dateList != null && dateList.size() > 0) {
            for(LocalDate date:dateList) {
                Double turnover = orderMapper.sumByDateTime(date,Orders.COMPLETED);
                //营业额若为空，则设为0
                turnover = (turnover == null ? 0.0 : turnover);
                turnoverList.add(turnover);
            }
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户数量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = getLocalDates(begin, end);

        //新增用户数列表
        List<Integer> totalUserList= new ArrayList<>();
        //总用户数列表
        List<Integer> newUserList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(dateList)) {
           for(LocalDate date:dateList){
               Map map = new HashMap<>();
               map.put("end", date);

               // 查询总用户数量
               Integer totalUser = userMapper.countByMap(map);
               totalUserList.add(totalUser);

               map.put("begin", date);
               // 查询新用户数量
               Integer newUser = userMapper.countByMap(map);
               newUserList.add(newUser);
           }
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单数量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = getLocalDates(begin, end);
        //订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        //有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        //订单总数
        Integer totalOrderCount = 0;
        //有效订单数
        Integer validOrderCount = 0;
        //订单完成率
        Double orderCompletionRate = 0.0;

        //遍历dateList
        if(dateList!=null && dateList.size()>0){
            for(LocalDate date:dateList) {
                //查询对应日期的总订单数
                Integer totalCount = orderMapper.getTotalCount(date,null);
                //查询对应日期的有效订单数
                Integer validCount = orderMapper.getTotalCount(date,Orders.COMPLETED);

                orderCountList.add(totalCount);
                validOrderCountList.add(validCount);
            }
        }

        //使用stream流完成订单数统计
        //时间区间内的总订单数
        totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率 =  有效订单数 / 订单总数
        if(totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() /totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .build();
    }

    /**
     * 查询指定时间区间内销量top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //获取销量top10，存储到goodsSales列表中
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10(begin,end);

        String nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //获取最近30天的运营数据
        LocalDate localDate = LocalDate.now();
        LocalDate beginDate = localDate.minusDays(30);
        LocalDate endDate = localDate.minusDays(1);

        //获取模板输入流
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx");
        //获取输入流
        ServletOutputStream outputStream = null;
        try {
            //通过输入流读取指定的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获取文件中指定的sheet页
            XSSFSheet sheet1 = excel.getSheet("sheet1");

            //获取具体需要填充数据的单元格
            //获取第二行，第二列
            XSSFRow row = sheet1.getRow(1);
            row.getCell(1).setCellValue("时间：" + beginDate + "至" + endDate);

            //查询近30天的数据详细信息
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));

            //获取第四行，第三、五、七列
             row = sheet1.getRow(3);
             row.getCell(2).setCellValue(businessData.getTurnover());
             row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
             row.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行，第三、五列
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //获取详细30天内每天的详细数据
            for (int i = 0; i < 30; i++) {

                //获取第几行
                row = sheet1.getRow(7 + i);
                //调用service查数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(beginDate, LocalTime.MAX));
                //固定列数赋值
                row.getCell(1).setCellValue(beginDate.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
                //更新时间
                beginDate = beginDate.plusDays(1);
            }

            //导出文件
            outputStream = response.getOutputStream();
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 获取begin ~ end 之间日期
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = new ArrayList<>();
        //获取所有begin ~ end之间的所有date
        //compareTo：可以比较两个日期是否相等
        while(begin.compareTo(end)<=0) {
            dateList.add(begin);
            //日期计算，获得指定日期前1天的日期
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
